package com.df.bpm.utils.businessViewerV2.res;

import com.df.bpm.utils.businessViewerV2.Main;
import com.df.common.utils.CommonUtils;
import lombok.Getter;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public abstract class V_A<T> implements V_fastTable<T>{

    public static int unit=10;
    public JDialog jd=new JDialog();
    public JLayeredPane jp=new JLayeredPane();
    Font iFont;

    public List<String> colNames;

    public List<String> keyCols;

    JScrollPane scr=new JScrollPane();

    public T selectResult;

    @Getter
    List<JTextField> fields=new ArrayList<>();


    public SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public Window thisWindow;

    public V_A() {
        unit= (int) Main.unit;
        iFont=new Font("宋体", Font.PLAIN, unit);
        jd.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
                // 关闭窗口时触发
            }
        });
        jd.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        jd.setSize(40*unit, 30*unit);
        setDialogSize(40*unit, 30*unit);
        colNames=getColNames();
        keyCols=getKeyCols();
    }


    private void repaintBase() {
        for(String colName:keyCols){
            if(keyCols.contains(colName) && !colName.equals("序号")) {
                addFields(fields, colName, unit, iFont, jp);
            }
        }


        JTextField lastField=fields.get(fields.size()-1);

        scr.setLocation(unit,lastField.getY()+lastField.getHeight()+unit);
        scr.setSize(jp.getWidth()-3*unit, jp.getHeight()-4*unit-scr.getY());
        jp.add(scr);

        for(JTextField field:fields){
            field.addKeyListener(
                    new KeyAdapter(){
                        public void keyPressed(KeyEvent e)
                        {
                            if(e.getKeyChar()==KeyEvent.VK_ENTER )   //按回车键执行相应操作;
                            {
                                try {
                                    search(fields);
                                } catch (Exception ex) {
                                    throw new RuntimeException(ex);
                                }
                            }
                        }
                    });
        }

        putModel(null);
    }

    public void repaint() {
        thisWindow=jd;
        jd.remove(jp);
        jd.setLocationRelativeTo(null);
        jd.setLayout(null);
        jp=new JLayeredPane();
        jp.setLayout(null);
        jp.setSize(jd.getSize());

        repaintBase();


        JPanel panel2 = new JPanel();
        panel2.setBackground(Color.BLUE);
        panel2.setOpaque(true);  // 确保面板是不透明的
        panel2.setPreferredSize(new Dimension(200, 100));
        panel2.setLocation(50, 50);  // 设置面板的位置（可选）
        jp.add(panel2);
        jp.setLayer(panel2, JLayeredPane.DEFAULT_LAYER + 1);

        jd.add(jp);

        jd.setModal(true);
        jd.repaint();
        fields.get(0).requestFocus();

    }

    public void repaint(JFrame jf) {
        thisWindow=jf;
        jf.remove(jp);
        jp=new JLayeredPane();
        jp.setLayout(null);
        jp.setSize(jf.getSize());

        repaintBase();

        jf.add(jp);
        jf.repaint();
        fields.get(0).requestFocus();
    }



    public void setVisible(boolean isVisible){
        jd.setVisible(isVisible);
    }

    static void addFields(List<JTextField> fields, String colName, int unit, Font iFont, JLayeredPane jp) {
        JTextField iField=new JTextField();
        iField.setBounds(unit +fields.size()*(7* unit), unit,6* unit, (int) (2.5* unit));
        iField.setFont(iFont);
        iField.setBorder(BorderFactory.createTitledBorder(colName));
        fields.add(iField);
        jp.add(iField);
    }

    public void putModel(List<T> list) {
        scr.getViewport().removeAll();
        String[] title=colNames.toArray(new String[0]);
        int sequenceCol=colNames.indexOf("序号");
        DefaultTableModel model = new DefaultTableModel(null, title){
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return false;//不允许编辑，留作触发双击或拖拽
            }
        };
        if(CommonUtils.varIsNotBlank(list)) {
            for (T row : list) {
                Object[] oRow=getRowValues(row);
                if(sequenceCol!=-1){//序号列计算序号倒序
                    oRow[sequenceCol]=list.size()-model.getRowCount();
                }
                model.addRow(oRow);
            }
        }else{
            list=new ArrayList<>();
        }
        model.addRow(new Object[colNames.size()]);
        list.add(getEmptyRow());
        JTable iTable=newTable(model, iFont);
        fixColWidth(iTable);
        hideCol(iTable);
        scr.getViewport().add(iTable);
        iTable.addMouseListener(mouseAdapter4Table(iTable,list));
    }

    private void fixColWidth(JTable iTable) {
        List<Integer> newColWidths=colWidthSetting();
        if(CommonUtils.varIsBlank(newColWidths)){
            iTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        }else{
            iTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            for(int i=0;i<newColWidths.size();i++){
                iTable.getColumnModel().getColumn(i).setPreferredWidth(newColWidths.get(i)*unit);
            }
        }
    }



    static JTable newTable(DefaultTableModel model, Font iFont) {
        JTable iTable = new JTable(model);
        iTable.getTableHeader().setFont(new Font("宋体", Font.BOLD, (int) (unit*1.1)));
        iTable.setFont(iFont);
        iTable.setRowHeight((unit+1));
        iTable.getColumnModel().getColumn(1).setPreferredWidth(10);
        iTable.getColumnModel().getColumn(2).setPreferredWidth(100);
        return iTable;
    }

    /**
     * 获取要作为搜索框的字段
     * @return  作为搜索框的字段
     */
    public abstract List<String> getKeyCols();


    public abstract void search(List<JTextField> fields) throws Exception;


    public abstract void setDialogSize(int width, int height);

    public void search() throws Exception {
        search(fields);
    }


}
